<?php

class StaticPagesController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return Yii::app()->GetAccessRule->get();
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new StaticPages;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['StaticPages']))
		{
			$model->attributes=$_POST['StaticPages'];
			//echo '<pre>'; print_r($model->attributes);exit;
			
			$model->slug= $this->behaviors();
			// print_r($model->attributes);exit;
			if($model->type=='image')
			{
				$type_array = array("jpg","jpeg","gif","png");
				
				$temp= CUploadedFile::getInstance($model,'attachment');
				if(!empty($temp))
				{	
					$name=$temp->getName();
					$extension = substr($name, strpos($name, '.')+1);
					if(in_array(strtolower($extension),$type_array))
					{
						//echo ApplicationSessions::run()->read('dentist_id');exit;
						$name=md5($name.time()).'.'.$extension;
						$model->attachment=$name;
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['uploads']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['uploads']);
						}
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['staticpages']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['staticpages']);
						}
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['staticpagesLarge']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['staticpagesLarge']);
						}
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['staticpagesSmall']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['staticpagesSmall']);
						}
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['staticpagesMid']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['staticpagesMid']);
						}
						
						$temp->saveAs(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'] . '/'. $name );
					    copy(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'] . '/'. $name , ApplicationConfig::app()->params['folder_path']['staticpagesSmall'] . '/'. $name );
						copy(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'] . '/'. $name , ApplicationConfig::app()->params['folder_path']['staticpagesMid'] . '/'. $name );
						
						//resize mid img
					    $image = Yii::app()->image->load(ApplicationConfig::app()->params['folder_path']['staticpagesMid'] . '/'.$name);
						$dim = BackendApplicationConfig::getImagedimensions('mid');
					    $image->resize($dim['width'], $dim['height']);
						$image->save();
						
						//resize small img
					    $image = Yii::app()->image->load(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'] . '/'.$name);
						$dim = BackendApplicationConfig::getImagedimensions('small');
					    $image->resize($dim['width'], $dim['height']);
						$image->save();
					}
				}
			}
/*            else if($model->type=='video')
			{
				$modelObject = CUploadedFile::getInstance($model, 'attachment');
				//$model->attachment = $modelObject;
				$type = explode(".", $modelObject);
	  
				if (!empty($modelObject))
				{
						$type_array = array("flv","wmv","m4v","avi","mp4");
						$interval = 0;
						$size = '150x100';
						$name=md5($modelObject->name . time()) ;
						$attachment = $name . '.' . $type[1];
						if(in_array(strtolower($type[1]),$type_array))
						{
							//$model->attachment = $attachment;
							
							if(!is_dir(YiiBase::getPathOfAlias('webroot.uploads.news')))
							{
								mkdir(YiiBase::getPathOfAlias('webroot.uploads.news'));
										
							}
							if(!is_dir(YiiBase::getPathOfAlias('webroot.uploads.news.videoorigional')))
							{
								mkdir(YiiBase::getPathOfAlias('webroot.uploads.news.videoorigional'));
										
							}
							if(!is_dir(YiiBase::getPathOfAlias('webroot.uploads.news.videoconverted')))
							{
								mkdir(YiiBase::getPathOfAlias('webroot.uploads.news.videoconverted'));
										
							}
							if(!is_dir(YiiBase::getPathOfAlias('webroot.uploads.news.videothumb')))
							{
								mkdir(YiiBase::getPathOfAlias('webroot.uploads.news.videothumb'));
										
							}
							$orgvideo = YiiBase::getPathOfAlias('webroot.uploads.news.videoorigional') . '/'.
								$attachment;
							$modelObject->saveAs(YiiBase::getPathOfAlias('webroot.uploads.news.videoorigional') . '/'.
								$attachment);
							$convertedvideo = YiiBase::getPathOfAlias('webroot.uploads.news.videoconverted') . '/'.
								$name . '.flv';
							$thumbnail = YiiBase::getPathOfAlias('webroot.uploads.news.videothumb') . '/'.
								$name . '.jpeg';
							if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
							{
								$orgvideo = str_replace('\\', '\\\\', $orgvideo);
								$convertedvideo = str_replace('\\', '\\\\', $convertedvideo);
								$thumbnail = str_replace('\\', '\\\\', $thumbnail);
								exec("ffmpeg -i $orgvideo -deinterlace -an -ss $interval -f mjpeg -t 1 -r 1 -y -s $size $thumbnail 2>&1");
								exec("ffmpeg -i $orgvideo -s 320x240 $convertedvideo");
							} 
							else
							{
								shell_exec("ffmpeg -i $orgvideo -deinterlace -an -ss $interval -f mjpeg -t 1 -r 1 -y -s $size $thumbnail 2>&1");
								shell_exec("ffmpeg -i $orgvideo -s 320x240 $convertedvideo");
							}

							$model->attachment = $name.'.flv';
						}
						
				}
				
			}*/
			else if($model->type=='none')
			{
			$model->attachment='';
			}
			else if($model->type=='')
			{
			$model->attachment='';
			}
			//slug genration starts here
			
			$title = $_POST['StaticPages']['title'];
            $select = array('title','slug', 'staticpage_id');
            $condition = array('title');
            $params = array('title' => $_POST['StaticPages']['title']);
            $arrResult = SlugGenerate::getSlug(Yii::app()->params['tbl_prefix'] .
                'static_pages', $condition, $params, $select);
            if ($arrResult != "NO-MATCH")
            {
                $model->slug = $arrResult;
            }
			else
            {

                $slug = SlugGenerate::getFormattedSlug($title);
                $model->slug = $slug;
            }
			
			//echo '<pre>'; print_r($model->attributes);exit;
			//slug genration ends here
			
			if($model->save())
			{
				//$this->redirect(array('view','id'=>$model->staticpage_id));
				$this->redirect(ApplicationConfig::getURL('user', 'staticPages', 'admin'));
			}
			
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$old=$model->title;
		$prevtype=$model->type;
		$previmage=isset($model->attachment)?$model->attachment:'';
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['StaticPages']))
		{
		
			$model->attributes=$_POST['StaticPages'];
			$model->slug= $this->behaviors();
			
			if($model->type=='image')
			{
				$temp= CUploadedFile::getInstance($model,'attachment');
				if(!empty($temp))
				{
					$name=$temp->getName();
					$extension = substr($name, strpos($name, '.')+1);
					$type_array = array("jpg","jpeg","gif","png");
					if(in_array(strtolower($extension),$type_array))
					{
						$name=md5($name.time()).'.'.$extension;
						$model->attachment=$name;
						//delete old images
						if($previmage != "")
						{
							if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'].'/'. $previmage))
							{
								unlink(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'].'/'. $previmage);
							}
							if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesMid'].'/'. $previmage))
							{
								unlink(ApplicationConfig::app()->params['folder_path']['staticpagesMid'].'/'. $previmage);
							}
							if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'].'/'. $previmage))
							{
								unlink(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'].'/'. $previmage);
							}
						}
						
						//create directory
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['uploads']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['uploads']);
						}
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['staticpages']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['staticpages']);
						}
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['staticpagesLarge']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['staticpagesLarge']);
						}
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['staticpagesSmall']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['staticpagesSmall']);
						}
						if(!is_dir(ApplicationConfig::app()->params['folder_path']['staticpagesMid']))
						{
							mkdir(ApplicationConfig::app()->params['folder_path']['staticpagesMid']);
						}
						
						$temp->saveAs(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'] . '/'. $name );
					    copy(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'] . '/'. $name , ApplicationConfig::app()->params['folder_path']['staticpagesSmall'] . '/'. $name );
						copy(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'] . '/'. $name , ApplicationConfig::app()->params['folder_path']['staticpagesMid'] . '/'. $name );
						
						//resize mid img
					    $image = Yii::app()->image->load(ApplicationConfig::app()->params['folder_path']['staticpagesMid'] . '/'.$name);
						$dim = BackendApplicationConfig::getImagedimensions('mid');
					    $image->resize($dim['width'], $dim['height']);
						$image->save();
						
						//resize small img
					    $image = Yii::app()->image->load(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'] . '/'.$name);
						$dim = BackendApplicationConfig::getImagedimensions('small');
					    $image->resize($dim['width'], $dim['height']);
						$image->save();
					}
				}
				else
				{
					$model->attachment=$previmage;
				}
			}
/*            else if($model->type=='video')
			{
				$modelObject = CUploadedFile::getInstance($model, 'attachment');
				if(!empty($modelObject))
				{
					//$model->attachment = $modelObject;
					$type = explode(".", $modelObject);
		  
					if (!empty($modelObject))
					{
							$interval = 0;
							$size = '150x100';
							$name=md5($modelObject->name . time()) ;
							$type_array = array("flv","wmv","m4v","avi","mp4");
							if(in_array(strtolower($type[1]),$type_array))
							{
								$attachment = $name . '.' . $type[1];
								//$model->attachment = $attachment;
								
								if(!is_dir(YiiBase::getPathOfAlias('webroot.uploads.news')))
								{
									mkdir(YiiBase::getPathOfAlias('webroot.uploads.news'));
											
								}
								if(!is_dir(YiiBase::getPathOfAlias('webroot.uploads.news.videoorigional')))
								{
									mkdir(YiiBase::getPathOfAlias('webroot.uploads.news.videoorigional'));
											
								}
								if(!is_dir(YiiBase::getPathOfAlias('webroot.uploads.news.videoconverted')))
								{
									mkdir(YiiBase::getPathOfAlias('webroot.uploads.news.videoconverted'));
											
								}
								if(!is_dir(YiiBase::getPathOfAlias('webroot.uploads.news.videothumb')))
								{
									mkdir(YiiBase::getPathOfAlias('webroot.uploads.news.videothumb'));
											
								}
								$orgvideo = YiiBase::getPathOfAlias('webroot.uploads.news.videoorigional') . '/'.
									$attachment;
								$modelObject->saveAs(YiiBase::getPathOfAlias('webroot.uploads.news.videoorigional') . '/'.
									$attachment);
								$convertedvideo = YiiBase::getPathOfAlias('webroot.uploads.news.videoconverted') . '/'.
									$name . '.flv';
								$thumbnail = YiiBase::getPathOfAlias('webroot.uploads.news.videothumb') . '/'.
									$name . '.jpeg';
								if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
								{
									$orgvideo = str_replace('\\', '\\\\', $orgvideo);
									$convertedvideo = str_replace('\\', '\\\\', $convertedvideo);
									$thumbnail = str_replace('\\', '\\\\', $thumbnail);
									exec("ffmpeg -i $orgvideo -deinterlace -an -ss $interval -f mjpeg -t 1 -r 1 -y -s $size $thumbnail 2>&1");
									exec("ffmpeg -i $orgvideo -s 320x240 $convertedvideo");
								} 
								else
								{
									shell_exec("ffmpeg -i $orgvideo -deinterlace -an -ss $interval -f mjpeg -t 1 -r 1 -y -s $size $thumbnail 2>&1");
									shell_exec("ffmpeg -i $orgvideo -s 320x240 $convertedvideo");
								}

								$model->attachment = $name.'.flv';
							}
							
					}
					else
					{
						$model->attachment=$previmage;
					}
				}
				
			}*/
			else if($model->type=='none')
			{
				if($prevtype="image")
				{
					if($previmage != "")
					{
						if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'].'/'. $previmage))
						{
							unlink(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'].'/'. $previmage);
						}
						if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesMid'].'/'. $previmage))
						{
							unlink(ApplicationConfig::app()->params['folder_path']['staticpagesMid'].'/'. $previmage);
						}
						if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'].'/'. $previmage))
						{
							unlink(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'].'/'. $previmage);
						}
					}
				}
				$model->attachment='';
			}
			else if($model->type=='')
			{
			    if($prevtype="image")
				{
					if($previmage != "")
					{
						if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'].'/'. $previmage))
						{
							unlink(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'].'/'. $previmage);
						}
						if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesMid'].'/'. $previmage))
						{
							unlink(ApplicationConfig::app()->params['folder_path']['staticpagesMid'].'/'. $previmage);
						}
						if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'].'/'. $previmage))
						{
							unlink(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'].'/'. $previmage);
						}
					}
				}
				$model->attachment='';
			}
			//slug genration starts here
			if($_POST['StaticPages']['title'] != $old)
			{
			
			$title = $_POST['StaticPages']['title'];
            $select = array('title','slug', 'staticpage_id');
            $condition = array('title');
            $params = array('title' => $_POST['StaticPages']['title']);
            $arrResult = SlugGenerate::getSlug(Yii::app()->params['tbl_prefix'] .
                'static_pages', $condition, $params, $select);
            if ($arrResult != "NO-MATCH")
            {
                $model->slug = $arrResult;
            }
			else
            {

                $slug = SlugGenerate::getFormattedSlug($title);
                $model->slug = $slug;
            }
			}
			
			//slug genration ends here
			if($model->save())
			{
				//$this->redirect(array('view','id'=>$model->staticpage_id));
				$this->redirect(ApplicationConfig::getURL('user', 'staticPages', 'admin'));
			}
			else
			{
			   // print_r($model->getErrors());
			}
		}
		//if(isset($_POST['StaticPages']))
		//{
			//$model->attributes=$_POST['StaticPages'];

			//if($model->save())
				//$this->redirect(ApplicationConfig::getURL('user', 'staticPages', 'admin'));
				
		//}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
			$model = $this->loadModel($id);
			$previmage=isset($model->attachment)?$model->attachment:'';
			
			if($previmage != "")
			{
				if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'].'/'. $previmage))
				{
					unlink(ApplicationConfig::app()->params['folder_path']['staticpagesLarge'].'/'. $previmage);
				}
				if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesMid'].'/'. $previmage))
				{
					unlink(ApplicationConfig::app()->params['folder_path']['staticpagesMid'].'/'. $previmage);
				}
				if(file_exists(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'].'/'. $previmage))
				{
					unlink(ApplicationConfig::app()->params['folder_path']['staticpagesSmall'].'/'. $previmage);
				}
			}
			
			$model->delete();
			
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('StaticPages');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new StaticPages('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['StaticPages']))
			$model->attributes=$_GET['StaticPages'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return StaticPages the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=StaticPages::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param StaticPages $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='static-pages-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	
}
